package org.xx.armory.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import static org.xx.armory.commons.Validators.rejectIfBlank;

public final class OSSResource {
    private final String endPoint;

    private final String accessKey;

    private final String secretKey;

    public OSSResource(
            String endPoint,
            String accessKey,
            String secretKey
    ) {
        this.endPoint = rejectIfBlank(endPoint, "endPoint").strip();
        this.accessKey = rejectIfBlank(accessKey, "accessKey").strip();
        this.secretKey = rejectIfBlank(secretKey, "secretKey").strip();
    }

    /**
     * 创建一个针对OSS的包装对象。
     *
     * @return 针对OSS的包装对象。
     */
    public final synchronized OSSWrapper wrap() {
        return new OSSWrapper();
    }

    public final class OSSWrapper
            implements AutoCloseable {
        private final OSS oss;

        private OSSWrapper() {
            this.oss = new OSSClientBuilder().build(endPoint, accessKey, secretKey);
        }

        public OSS getOss() {
            return this.oss;
        }

        @Override
        public void close()
                throws Exception {
            this.oss.shutdown();
        }
    }
}
